<?php

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\validate\OrderPlace;
use app\api\service\Order as OrderService;
use app\api\service\Token as TokenService;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\PagingParamter;
use app\lib\exception\OrderException;
use app\api\model\Order as OrderModel;

class Order extends BaseController
{
    
    /**
     * 
     * @api {POST} /placce 下单操作
     * @apiName placeOrder
     * @apiGroup Order
     * @apiVersion  1.0.0
     * 
     * 
     * @apiParam  {Object} products 产品库存及ID
     * 
     * @apiSuccess (200) {Object} order 订单详情
     * 
     */
    public function placeOrder($products)
    {
        (new OrderPlace())->goCheck();
        $oProducts = $products;
        $uid = TokenService::getCurrentUID();
        $orderService = new OrderService();
        $order = $orderService->place($uid,$oProducts);
        return $order;
    }

    /**
     * 
     * @api {GET} /order/:id 获取订单详情
     * @apiName orderDetail
     * @apiGroup Order
     * @apiVersion  1.0.0
     * 
     * 
     * @apiParam  {Integer} ID 订单ID
     * 
     * @apiSuccess (200) {Object} orderDetail 订单详情
     * 
     */
    public function orderDetail($id)
    {
        (new IDMustBePositiveInt())->goCheck();
        $orderDetail = OrderModel::getOrderDetailByID($id);
        if(!$orderDetail){
            throw new OrderException([
                'msg' => '订单未找到',
            ]);
        }
        return $orderDetail;
    }

    /**
     * 
     * @api {POST} /order/by_user 获取用户历史订单
     * @apiName getSummaryUser
     * @apiGroup Order
     * @apiVersion  1.0.0
     * 
     * 
     * @apiParam  {Integer} size 条数
     * @apiParam  {Integer} page 当前页
     * 
     * @apiSuccess (200) {Object} order 订单列表
     * 
     */
    public function getSummaryUser($page=1,$size=15)
    {
        // 校验page与size参数
        (new PagingParamter())->goCheck();
        $uid = TokenService::getCurrentUid();
        $pagingOrders = OrderModel::getSummaryByUser($uid,$page,$size);
        if($pagingOrders->isEmpty()){
            return [
                'data' => [],
                'current_page' => $pagingOrders->getCurrentPage(),
            ];
        }
        $data = $pagingOrders->toArray();
        return [
            'data' => $data,
            'current_page' => $pagingOrders->getCurrentPage(),
        ];
    }

}
